<template>
  <div class="topic-form">
    <el-form ref="ruleForm" :rules="rules" :model="model" label-width="160px">
      <el-row :gutter="10">
        <el-col :span="22">
          <el-form-item label="代码段名称" prop="name">
            <el-input v-model="model.name" name="name">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="模板代码" prop="note">
            <scCodeEditor v-model="model.note" name="note" mode="sql" style="width: 100%;height: auto">
            </scCodeEditor>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item>
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import {defineAsyncComponent, ref} from "vue";

const scCodeEditor = defineAsyncComponent(() => import('@/components/scCodeEditor/index.vue'));

// 定义emit
const emit = defineEmits(['submit', 'cancel']);

// 表单数据
const model = defineModel({
  default: () => ({})
});

// 验证规则
const rules = ref({});

const ruleForm = ref(null);

// 处理提交
const handleSubmit = async () => {
  if (!ruleForm.value) return;

  try {
    await ruleForm.value.validate();
    emit('submit', model.value);
  } catch (error) {
    console.log('表单验证失败', error);
  }
};

// 处理取消
const handleCancel = () => {
  emit('cancel');
};

// 暴露表单引用给父组件
defineExpose({
  ruleForm,
  validate: () => ruleForm.value?.validate(),
  resetFields: () => ruleForm.value?.resetFields()
});
</script>

<style scoped>
.topic-form {
  width: 100%;
}
</style>
